package c04.reentrantlock;

import lombok.extern.slf4j.Slf4j;
import util.Sleeper;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试可中断
 * 
 */
@Slf4j(topic = "c.InterruptTest1")
public class InterruptTest1 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            log.debug("{} 启动...", Thread.currentThread().getName());
            try {
                // 如果没有竞争，那么此方法就会获取lock对象锁
                // 如果有竞争，就进入阻塞队列，可以被其他线程用 interrupt 方法打断
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("{} 等锁的过程中被打断", Thread.currentThread().getName());
                return;
            }

            try {
                log.debug("{} 获得了锁", Thread.currentThread().getName());
            } finally {
                lock.unlock();
                log.debug("{} 释放锁", Thread.currentThread().getName());
            }
        }, "t1");

        lock.lock();
        log.debug("{} 获得了锁", Thread.currentThread().getName());
        t1.start();
        try {
            Sleeper.sleep(1);
            t1.interrupt();
            log.debug("{} 执行了打断", Thread.currentThread().getName());
        } finally {
            lock.unlock();
            log.debug("{} 释放了锁", Thread.currentThread().getName());
        }
    }
}
